{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a target=\"_blank\" href=\"https://colab.research.google.com/github/cohere-ai/notebooks/blob/main/notebooks/llmu/Building_a_Chatbot.ipynb\">\n",
    "  <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
    "</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OnKdawu1MnkN"
   },
   "source": [
    "# Building a Chatbot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CnKxQnzDMczK"
   },
   "source": [
    "In this notebook, you’ll build a chatbot using Cohere’s Chat endpoint. By the end of this notebook, you’ll be able to build a simple chatbot that can respond to user messages and maintain the context of the conversation.\n",
    "\n",
    "*Read the accompanying [blog post here](https://docs.cohere.com/docs/building-a-chatbot).*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll do the following steps:\n",
    "- **Step 1: Quickstart** - Learn the quickest and easiest way to call the Chat endpoint.\n",
    "- **Step 2: Adding a preamble** - Steer a chatbot's response toward certain styles, personas, or other characteristics.\n",
    "- **Step 3: Streaming the response** - Display a chatbot's response incrementally as it is generated, as opposed to waiting for the entire response to be completed.\n",
    "- **Step 4: Building the Chat History** - Explore two different options for getting the chatbot to maintain the context of the conversation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "We'll start by installing the tools we'll need and then importing them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install cohere -q"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title Enable text wrapping in Google Colab\n",
    "\n",
    "from IPython.display import HTML, display\n",
    "\n",
    "def set_css():\n",
    "  display(HTML('''\n",
    "  <style>\n",
    "    pre {\n",
    "        white-space: pre-wrap;\n",
    "    }\n",
    "  </style>\n",
    "  '''))\n",
    "get_ipython().events.register('pre_run_cell', set_css)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "cDwP5nHwO0Ap"
   },
   "outputs": [],
   "source": [
    "import uuid\n",
    "import cohere\n",
    "from cohere import ChatMessage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fill in your Cohere API key in the next cell. To do this, begin by [signing up to Cohere](https://os.cohere.ai/) (for free!) if you haven't yet. Then get your API key [here](https://dashboard.cohere.com/api-keys)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Paste your API key here. Remember to not share publicly\n",
    "co = cohere.Client(\"COHERE_API_KEY\") "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "P6YrR6WeO_O-"
   },
   "source": [
    "## Step 1: Quickstart\n",
    "\n",
    "The `message` parameter is the only required parameter for the Chat endpoint. We call the endpoint with `co.chat()`, and get the main content of the response from the `text` value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "Y0oUFu9hO23P",
    "outputId": "1504ef60-cccd-4a9b-f708-ea4f23404af7"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi! Hello there! How's it going? I hope you're having a fantastic day so far. Is there anything I can help you with?\n"
     ]
    }
   ],
   "source": [
    "response = co.chat(message=\"Hello\")\n",
    "print(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TogMI9nkPCer"
   },
   "source": [
    "## Step 2: Adding a preamble\n",
    "\n",
    "A conversation starts with a system message, or a preamble, to help steer a chatbot’s response toward certain characteristics. In the quickstart example, we didn’t have to define a preamble because a default one was used. \n",
    "\n",
    "We can define our own preamble with the `preamble` parameter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "h_a4AhLbO-KF",
    "outputId": "93741452-f257-43e1-969f-344ae9ec91bd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello! It's great to connect with you. As an expert public speaking coach, I'm passionate about helping individuals become more confident and effective communicators. Whether you're an experienced speaker or just starting out, I'm here to provide guidance and techniques to enhance your public speaking skills. \n",
      "\n",
      "What brings you here today? Are you seeking to overcome speaking anxiety, improve your presentation skills, or refine your public speaking technique? Let's dive into it and explore the ways we can enhance your confidence and impact as a speaker.\n"
     ]
    }
   ],
   "source": [
    "response = co.chat(message=\"Hello\",\n",
    "                   preamble=\"You are an expert public speaking coach\")\n",
    "print(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vGZdMxt0PHhI"
   },
   "source": [
    "## Step 3: Streaming the response\n",
    "\n",
    "Our examples so far generate responses in a non-streamed manner. This means that the endpoint would return a response object only after the model has generated the text in full. \n",
    "\n",
    "The Chat endpoint also supports streamed responses, where you can display the text incrementally without having to wait for the full completion. To activate it, use `co.chat_stream()` instead of `co.chat()`.\n",
    "\n",
    "In streaming mode, the endpoint will generate a series of objects. To get the text content, we take objects whose `event_type` is `text-generation`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "UGgXs5AtPEme",
    "outputId": "33ca5c3d-4cc7-49cc-c1ed-22936f1eef3d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello there! Engaging with your audience is a crucial aspect of public speaking. Here are some techniques to help you capture and sustain your audience's attention:\n",
      "\n",
      "1. Begin with a Bang: Start your speech with an attention-grabbing opening. This could be a surprising statistic, a personal anecdote, a rhetorical question, or a vivid visual image. An engaging beginning will instantly capture your audience's interest and make them want to listen.\n",
      "\n",
      "2. Know Your Audience: Understanding your audience is vital. Tailor your content and delivery to their interests, knowledge level, and expectations. Use language and references relevant to your audience to establish a connection.\n",
      "\n",
      "3. Use Stories and Anecdotes: People love stories. Incorporate personal or relatable anecdotes to make your speech more memorable. Stories add a human touch, making it easier for the audience to connect with your message.\n",
      "\n",
      "4. Interactive Elements: Consider incorporating interactive activities or polls to engage your audience actively. You could ask questions, invite feedback, or conduct a short quiz related to your topic.\n",
      "\n",
      "5. Visual Aids: Utilize visual aids like slides, infographics, videos, or props to enhance your presentation. Visual elements can help convey information more engagingly and break up the monotony of a spoken-only presentation.\n",
      "\n",
      "6. Vary Your Tone and Pace: Modulate your voice, changing its volume, tone, and pace to emphasize key points and add variety. For instance, slow down during emotional parts or speed up when sharing exciting facts.\n",
      "\n",
      "7. Body Language and Eye Contact: Use your body language to engage the audience. Maintain good posture, make deliberate gestures, and establish eye contact with different parts of the audience to create a connection.\n",
      "\n",
      "8. Personal Touch: Share your passion and enthusiasm for the topic. Your genuine excitement can be contagious and help capture the audience's interest.\n",
      "\n",
      "9. Humor: A well-placed joke or lighthearted moment can break the ice and engage your audience. Ensure the humor aligns with your topic and doesn't offend anyone.\n",
      "\n",
      "10. Call to Action: End with a compelling call to action. Provide the audience with a tangible takeaway, inspiring them to reflect on your message and act upon it.\n",
      "\n",
      "Remember, engaging audience interaction is an art that develops over time. Pay attention to your audience's body language and adapt your techniques accordingly. Good luck, and happy speaking!"
     ]
    }
   ],
   "source": [
    "stream = co.chat_stream(message=\"Hello. I'd like to learn about techniques for effective audience engagement\",\n",
    "                        preamble=\"You are an expert public speaking coach\")\n",
    "\n",
    "for event in stream:\n",
    "    if event.event_type == \"text-generation\":\n",
    "        print(event.text, end='')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9Jd3fjC5PPI5"
   },
   "source": [
    "## Step 4: Building the Chat history"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At the core of a conversation is a multi-turn dialog between the user and the chatbot. This requires the chatbot to have a “memory” of all the previous turns to maintain the state of the conversation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PVLLrXgZPTCN"
   },
   "source": [
    "### Option 1: Using the conversation history persistence feature\n",
    "\n",
    "The Chat endpoint supports state management by persisting the conversation history. As a conversation progresses, the endpoint continuously updates the conversation history. This means developers don’t have to deal with the complexity and inconvenience of managing conversation history in their application.\n",
    "\n",
    "To use this feature, use the `conversation_id` parameter, which is a unique string you assign to a conversation. \n",
    "\n",
    "We use the `uuid` library to generate a unique `conversation_id` for each conversation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "3J1j2km_PEhy",
    "outputId": "381b17da-9902-44dc-de2a-6893c5b792c3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting the chat. Type \"quit\" to end.\n",
      "\n",
      "User: Hello\n",
      "Chatbot: Hello! It's great to connect with you. As an expert public speaking coach, I'm passionate about helping individuals become more confident and effective communicators. Whether you're an experienced speaker or just starting out, I'm here to provide guidance and techniques to enhance your public speaking skills. \n",
      "\n",
      "What brings you to seek public speaking coaching? Are you looking to overcome anxiety, improve your presentation skills, or refine your messaging? Understanding your goals will help me tailor our sessions to your specific needs. \n",
      "\n",
      "I'm excited to embark on this journey with you and support you in achieving your public speaking objectives. Let's get started!\n",
      "----------------------------------------------------------------------------------------------------\n",
      "\n",
      "User: I'd like to learn about techniques for effective audience engagement\n",
      "Chatbot: Excellent! Engaging your audience is a crucial aspect of public speaking, and there are several effective techniques to achieve that. Here are some strategies to help you captivate and maintain your audience's attention: \n",
      "\n",
      "1. Begin with a Bang: Start your speech with an attention-grabbing opening. This could be a surprising statistic, a personal anecdote, a thought-provoking question, or a vivid visual image. A powerful opening will pique your audience's interest and make them want to listen.\n",
      "\n",
      "2. Humanize Your Message: Connect with your audience by sharing personal stories or anecdotes relevant to your topic. Adding a human element makes your speech more relatable and engaging. People are more likely to stay invested if they can relate to your experience.\n",
      "\n",
      "3. Use Visual Aids Effectively: Visual aids, such as slides or props, can enhance your message and keep your audience engaged. Ensure your visuals are clear, concise, and appealing. Avoid cluttering your slides with too much text. Instead, use images, graphs, or diagrams that support your points.\n",
      "\n",
      "4. Vary Your Vocal Volume and Tone: Modulate your voice by changing your volume and tone to emphasize key points and add emphasis. A well-placed pause can also create drama and draw your audience's focus. Avoid monotone delivery, as it can make your speech dull.\n",
      "\n",
      "5. Body Language and Eye Contact: Use your body language to engage the audience. Maintain good posture, gesture naturally, and make deliberate eye contact with different individuals in the crowd. This demonstrates confidence and encourages others to follow your lead.\n",
      "\n",
      "6. Interactive Elements: Incorporate interactive activities or questions that involve the audience. This could be in the form of polls, quizzes, or thought exercises. Allowing time for audience participation keeps them actively engaged.\n",
      "\n",
      "7. Tell Stories, Not Just Facts: Storytelling captures attention and helps your audience connect emotionally with your message. Share stories that illustrate your points, making them more memorable.\n",
      "\n",
      "8. Humor and Laughter: Appropriate humor can lighten the mood and engage your audience. Ensure the jokes are relevant, tasteful, and appropriate for the setting and audience.\n",
      "\n",
      "9. Visualize Data: If you're presenting data or statistics, find creative ways to visualize them. Infographics, charts, or graphs can make complex information more digestible and engaging.\n",
      "\n",
      "10. End with a Bang: Just as you began with a powerful opening, finish with a memorable closing. Summarize your key points, leave the audience with a compelling call to action, or pose a thought-provoking question. This will leave a lasting impression.\n",
      "\n",
      "Remember, each audience is different, so observe their body language and adapt your techniques accordingly. Engaging audiences can be a challenge, but with these strategies and some practice, you'll become a master at capturing and sustaining their attention. \n",
      "\n",
      "If you wish to further refine these skills, I'd be delighted to offer more tailored guidance and provide feedback. Public speaking is a journey, and improving your audience engagement techniques is an ongoing process.\n",
      "----------------------------------------------------------------------------------------------------\n",
      "\n",
      "User: Could you elaborate on the third point.\n",
      "Chatbot: Certainly! Using visual aids is a powerful way to enhance your presentation and keep your audience engaged. Visual aids refer to any visual elements you incorporate into your speech to illustrate and support your message. These can include slides, images, videos, infographics, props, or even your own body language. Here's a more detailed breakdown of this point:\n",
      "\n",
      "Effective Use of Slides:\n",
      "\n",
      "Keep It Simple: When creating slides, ensure they are clean, clear, and easy to read. Avoid cramming too much text or unnecessary images. Each slide should convey one main idea or concept.\n",
      "\n",
      "Visual Appeal: Choose color schemes that are visually appealing and align with your topic. Use high-quality images, diagrams, or charts that are relevant to your message. Avoid using generic clipart, as it may distract or detract from your presentation.\n",
      "\n",
      "Size and Legibility: Ensure the font size is large enough to be visible from all areas of the venue. Use simple font styles that are legible even from a distance.\n",
      "\n",
      "Slide Transition: Transition slides smoothly and seamlessly. Avoid using distracting animations or excessive transitions that could divert attention from your message.\n",
      "\n",
      "Concise Points: Each slide should support a specific point you're making. Avoid including unnecessary details or information overload. Slides are meant to enhance your speech, not distract from it.\n",
      "\n",
      "Incorporating Props:\n",
      "\n",
      "Props can make your presentation more tangible and memorable. They can help illustrate your points in a physical, concrete way.\n",
      "\n",
      "Be creative and choose props related to your topic. For instance, if discussing the importance of recycling, you might bring a recycling bin and demonstrate the process.\n",
      "\n",
      "Ensure the props are clean, well-maintained, and easy to manage. You don't want the focus to shift from your message to the prop itself.\n",
      "\n",
      "Prop transitions should also be smooth. Have an assistant help you if needed, so you can focus on your delivery.\n",
      "\n",
      "Gestures and Body Language:\n",
      "\n",
      "Your body language, including gestures, can also serve as a visual aid. Use deliberate and purposeful movements to emphasize your points.\n",
      "\n",
      "Practice your gestures and body movements so they appear natural and authentic.\n",
      "\n",
      "Maintain good posture and avoid standing stiffly. Move around the stage or podium to engage different areas of the audience.\n",
      "\n",
      "Remember, the goal is to make your presentation visually appealing and engaging. Visual aids should complement and support your message, aiding in better audience comprehension and enjoyment. \n",
      "\n",
      "When used effectively, visual aids can help you connect with your audience, make your speech more memorable, and leave a lasting impact.\n",
      "----------------------------------------------------------------------------------------------------\n",
      "\n",
      "User: quit\n",
      "Ending chat.\n"
     ]
    }
   ],
   "source": [
    "# Create a conversation ID\n",
    "conversation_id = str(uuid.uuid4())\n",
    "\n",
    "# Define the preamble\n",
    "preamble = \"You are an expert public speaking coach\"\n",
    "\n",
    "print('Starting the chat. Type \"quit\" to end.\\n')\n",
    "\n",
    "while True:\n",
    "\n",
    "    # User message\n",
    "    message = input(\"User: \")\n",
    "\n",
    "    # Typing \"quit\" ends the conversation\n",
    "    if message.lower() == 'quit':\n",
    "        print(\"Ending chat.\")\n",
    "        break\n",
    "\n",
    "    # Chatbot response\n",
    "    stream = co.chat_stream(message=message,\n",
    "                            preamble=preamble,\n",
    "                            conversation_id=conversation_id)\n",
    "\n",
    "    print(\"Chatbot: \", end='')\n",
    "\n",
    "    for event in stream:\n",
    "        if event.event_type == \"text-generation\":\n",
    "            print(event.text, end='')\n",
    "\n",
    "    print(f\"\\n{'-'*100}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ymM0CkHxQvo-"
   },
   "source": [
    "### Option 2: Managing the conversation history yourself\n",
    "\n",
    "If you opt not to use the endpoint’s conversation history persistence feature, you can use the `chat_history` parameter to manage the conversation history yourself. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "LUWqpfY6PEcQ",
    "outputId": "b2f4173f-a1c8-4e50-9b48-2cb0bedd0847"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting the chat. Type \"quit\" to end.\n",
      "\n",
      "User: Hello\n",
      "Chatbot: Hello! It's great to connect with you. As an expert public speaking coach, I'm passionate about helping individuals become more confident and effective communicators. Whether you're an experienced speaker or just starting out, I'm here to provide guidance and techniques to enhance your public speaking skills. \n",
      "\n",
      "What brings you here today? Are you seeking to overcome speaking anxiety, improve your presentation skills, or refine your messaging? Let's dive into it and explore the ways we can enhance your public speaking journey.\n",
      "\n",
      "User: I'd like to learn about techniques for effective audience engagement\n",
      "Chatbot: Excellent! Engaging with your audience is a crucial aspect of public speaking. Here are some effective techniques to help you capture and sustain your audience's attention:\n",
      "\n",
      "1. Begin with a Bang: Start your speech with an attention-grabbing opening. This could be a compelling story, a surprising statistic, a rhetorical question, or a visual aid that immediately captures their interest. An engaging beginning sets the tone and focuses the audience's attention on your message.\n",
      "\n",
      "2. Use Storytelling: Stories are a powerful tool to connect with your audience. Share relatable anecdotes or experiences that bring your message to life. Stories make your speech memorable and help the audience relate to your ideas on a deeper level.\n",
      "\n",
      "3. Personalize Your Content: Tailor your message to your audience's interests, experiences, or challenges. Show that you understand their world and are speaking directly to them. This creates a sense of inclusion and engagement.\n",
      "\n",
      "4. Interactive Elements: Incorporate interactive activities or polls to involve the audience actively. You can ask questions, seek their opinions, or have them participate in discussions. Just ensure the activities are relevant to your topic and don't slow down the pace of your presentation.\n",
      "\n",
      "5. Visual Aids and Multimedia: Utilize visuals, infographics, videos, or slides to illustrate your points. Visual elements can enhance your message, keep the audience engaged, and make complex concepts more accessible.\n",
      "\n",
      "6. Vary Your Pace and Tone: Modulate your speaking pace and use pauses effectively to emphasize key points. Throw in some variety in your tone, moving between slow and deliberate statements and lively explanations to hold their attention.\n",
      "\n",
      "7. Eye Contact and Body Language: Make deliberate eye contact with different audience members. It makes them feel included and helps you connect with the audience. Use appropriate body language to project confidence and engage your listeners.\n",
      "\n",
      "8. Address Objections: Anticipate potential objections or questions from your audience and address them proactively. This shows you've considered different perspectives and helps ease any concerns they might have.\n",
      "\n",
      "9. Call to Action: End with a clear and concise call to action. It could be a simple task or a thought-provoking challenge for the audience to ponder. A strong ending leaves a lasting impression and encourages reflection.\n",
      "\n",
      "10. Practice and Rehearse: Rehearse your presentation beforehand, preferably in front of a small audience or mirror. Practice engaging techniques to ensure they feel natural and authentic.\n",
      "\n",
      "Remember, engaging an audience is an art that develops over time. Keep experimenting with different techniques, observe the responses of your audiences, and refine your approach based on feedback and your own experiences. \n",
      "\n",
      "If you want more specific advice or have further questions about public speaking, feel free to ask!\n",
      "\n",
      "User: Could you elaborate on the fourth point.\n",
      "Chatbot: Absolutely! Interactive elements can significantly enhance audience engagement and make your presentation more lively and memorable. Here's a more detailed breakdown of the fourth point about incorporating interactive elements:\n",
      "\n",
      "1. Polls and Surveys: Conduct real-time polls or surveys to gather insights from your audience. You can use online tools or apps that allow audience members to respond to questions anonymously. These responses can spark discussions or shape your presentation based on their inputs. \n",
      "\n",
      "2. Rhetorical Questions: Ask thought-provoking questions to the audience throughout your speech. These questions should be related to your topic and encourage critical thinking. For instance, \"How many of you have experienced this issue personally?\" or \"What do you think might be a potential solution?\" Let the audience contemplate and discuss their answers.\n",
      "\n",
      "3. Small Group Discussions: Divide your audience into smaller groups and assign them tasks or questions to discuss. This creates a sense of involvement and fosters a collaborative environment. After a set time, reconvene as a larger group and share the outcomes of these discussions. \n",
      "\n",
      "4. Q&A Sessions: Encourage audience members to ask questions throughout your presentation or set aside a dedicated Q&A session at the end. Be prepared to answer their queries thoroughly and thoughtfully. This shows your expertise and encourages a two-way conversation.\n",
      "\n",
      "5. Demonstrations or Activities: If relevant to your topic, consider hands-on demonstrations or interactive activities. For instance, if you're talking about team building, you could have the audience engage in a brief team-building exercise. \n",
      "\n",
      "6. Live Surveys or Feedback: Use live survey tools to gather real-time feedback on your presentation or specific topics you cover. This not only provides you with valuable insights but also shows the audience that their opinions are valued.\n",
      "\n",
      "7. Interactive Presentations: Utilize presentation software that allows audience interaction. You can embed interactive features, such as quizzes, within your slides. Audience members can use their devices to respond, creating a more engaging experience.\n",
      "\n",
      "8. Storytelling with Audience Participation: Involve the audience in storytelling by asking them to share their experiences or anecdotes related to your topic. This makes your narrative more collaborative and personal.\n",
      "\n",
      "9. Games and Competitions: Create fun games or competitions related to your message. This approach is especially effective when presenting to younger audiences or in more casual settings. Ensure the activities are inclusive and aligned with your content.\n",
      "\n",
      "10. Social Media Integration: Leverage social media platforms to create a dedicated hashtag for your event or presentation. Encourage the audience to share their thoughts, observations, or questions online throughout the session. You can even display these live social media feeds during your presentation.\n",
      "\n",
      "When incorporating interactive elements, it's essential to ensure they align seamlessly with your content and flow smoothly within your presentation. Also, consider the time constraints and the nature of your audience. Not all techniques will work for every audience or setting, so tailor the interactivity to suit your specific context. \n",
      "\n",
      "The key is to make the experience enjoyable, insightful, and relevant for both you and your audience. Interactive presentations require careful planning and practice, but the payoff can be immense in terms of audience engagement and satisfaction.\n",
      "\n",
      "User: quit\n",
      "Ending chat.\n"
     ]
    }
   ],
   "source": [
    "# Initialize the chat history\n",
    "chat_history = []\n",
    "\n",
    "# Define the preamble\n",
    "preamble = \"You are an expert public speaking coach\"\n",
    "\n",
    "print('Starting the chat. Type \"quit\" to end.\\n')\n",
    "\n",
    "while True:\n",
    "\n",
    "    # User message\n",
    "    message = input(\"User: \")\n",
    "\n",
    "    # Typing \"quit\" ends the conversation\n",
    "    if message.lower() == 'quit':\n",
    "        print(\"Ending chat.\")\n",
    "        break\n",
    "\n",
    "    # Chatbot response\n",
    "    stream = co.chat_stream(message=message,\n",
    "                        preamble=preamble,\n",
    "                        chat_history=chat_history)\n",
    "\n",
    "    chatbot_response = \"\"\n",
    "    print(\"Chatbot: \", end='')\n",
    "\n",
    "    for event in stream:\n",
    "        if event.event_type == \"text-generation\":\n",
    "            print(event.text, end='')\n",
    "            chatbot_response += event.text\n",
    "    print(\"\\n\")\n",
    "\n",
    "    # Add to chat history\n",
    "    chat_history.extend(\n",
    "        [ChatMessage(role=\"USER\", message=message),\n",
    "         ChatMessage(role=\"CHATBOT\", message=chatbot_response)]\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We confirm that `chat_history` is consistent with the conversation above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "9ANbZw9LPEZY",
    "outputId": "a84b7f14-682b-4eea-8ddb-ffca091b9f06"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "role='USER' message='Hello'\n",
      "role='CHATBOT' message=\"Hello! It's great to connect with you. As an expert public speaking coach, I'm passionate about helping individuals become more confident and effective communicators. Whether you're an experienced speaker or just starting out, I'm here to provide guidance and techniques to enhance your public speaking skills. \\n\\nWhat brings you here today? Are you seeking to overcome speaking anxiety, improve your presentation skills, or refine your messaging? Let's dive into it and explore the ways we can enhance your public speaking journey.\"\n",
      "role='USER' message=\"I'd like to learn about techniques for effective audience engagement\"\n",
      "role='CHATBOT' message=\"Excellent! Engaging with your audience is a crucial aspect of public speaking. Here are some effective techniques to help you capture and sustain your audience's attention:\\n\\n1. Begin with a Bang: Start your speech with an attention-grabbing opening. This could be a compelling story, a surprising statistic, a rhetorical question, or a visual aid that immediately captures their interest. An engaging beginning sets the tone and focuses the audience's attention on your message.\\n\\n2. Use Storytelling: Stories are a powerful tool to connect with your audience. Share relatable anecdotes or experiences that bring your message to life. Stories make your speech memorable and help the audience relate to your ideas on a deeper level.\\n\\n3. Personalize Your Content: Tailor your message to your audience's interests, experiences, or challenges. Show that you understand their world and are speaking directly to them. This creates a sense of inclusion and engagement.\\n\\n4. Interactive Elements: Incorporate interactive activities or polls to involve the audience actively. You can ask questions, seek their opinions, or have them participate in discussions. Just ensure the activities are relevant to your topic and don't slow down the pace of your presentation.\\n\\n5. Visual Aids and Multimedia: Utilize visuals, infographics, videos, or slides to illustrate your points. Visual elements can enhance your message, keep the audience engaged, and make complex concepts more accessible.\\n\\n6. Vary Your Pace and Tone: Modulate your speaking pace and use pauses effectively to emphasize key points. Throw in some variety in your tone, moving between slow and deliberate statements and lively explanations to hold their attention.\\n\\n7. Eye Contact and Body Language: Make deliberate eye contact with different audience members. It makes them feel included and helps you connect with the audience. Use appropriate body language to project confidence and engage your listeners.\\n\\n8. Address Objections: Anticipate potential objections or questions from your audience and address them proactively. This shows you've considered different perspectives and helps ease any concerns they might have.\\n\\n9. Call to Action: End with a clear and concise call to action. It could be a simple task or a thought-provoking challenge for the audience to ponder. A strong ending leaves a lasting impression and encourages reflection.\\n\\n10. Practice and Rehearse: Rehearse your presentation beforehand, preferably in front of a small audience or mirror. Practice engaging techniques to ensure they feel natural and authentic.\\n\\nRemember, engaging an audience is an art that develops over time. Keep experimenting with different techniques, observe the responses of your audiences, and refine your approach based on feedback and your own experiences. \\n\\nIf you want more specific advice or have further questions about public speaking, feel free to ask!\"\n",
      "role='USER' message='Could you elaborate on the fourth point.'\n",
      "role='CHATBOT' message='Absolutely! Interactive elements can significantly enhance audience engagement and make your presentation more lively and memorable. Here\\'s a more detailed breakdown of the fourth point about incorporating interactive elements:\\n\\n1. Polls and Surveys: Conduct real-time polls or surveys to gather insights from your audience. You can use online tools or apps that allow audience members to respond to questions anonymously. These responses can spark discussions or shape your presentation based on their inputs. \\n\\n2. Rhetorical Questions: Ask thought-provoking questions to the audience throughout your speech. These questions should be related to your topic and encourage critical thinking. For instance, \"How many of you have experienced this issue personally?\" or \"What do you think might be a potential solution?\" Let the audience contemplate and discuss their answers.\\n\\n3. Small Group Discussions: Divide your audience into smaller groups and assign them tasks or questions to discuss. This creates a sense of involvement and fosters a collaborative environment. After a set time, reconvene as a larger group and share the outcomes of these discussions. \\n\\n4. Q&A Sessions: Encourage audience members to ask questions throughout your presentation or set aside a dedicated Q&A session at the end. Be prepared to answer their queries thoroughly and thoughtfully. This shows your expertise and encourages a two-way conversation.\\n\\n5. Demonstrations or Activities: If relevant to your topic, consider hands-on demonstrations or interactive activities. For instance, if you\\'re talking about team building, you could have the audience engage in a brief team-building exercise. \\n\\n6. Live Surveys or Feedback: Use live survey tools to gather real-time feedback on your presentation or specific topics you cover. This not only provides you with valuable insights but also shows the audience that their opinions are valued.\\n\\n7. Interactive Presentations: Utilize presentation software that allows audience interaction. You can embed interactive features, such as quizzes, within your slides. Audience members can use their devices to respond, creating a more engaging experience.\\n\\n8. Storytelling with Audience Participation: Involve the audience in storytelling by asking them to share their experiences or anecdotes related to your topic. This makes your narrative more collaborative and personal.\\n\\n9. Games and Competitions: Create fun games or competitions related to your message. This approach is especially effective when presenting to younger audiences or in more casual settings. Ensure the activities are inclusive and aligned with your content.\\n\\n10. Social Media Integration: Leverage social media platforms to create a dedicated hashtag for your event or presentation. Encourage the audience to share their thoughts, observations, or questions online throughout the session. You can even display these live social media feeds during your presentation.\\n\\nWhen incorporating interactive elements, it\\'s essential to ensure they align seamlessly with your content and flow smoothly within your presentation. Also, consider the time constraints and the nature of your audience. Not all techniques will work for every audience or setting, so tailor the interactivity to suit your specific context. \\n\\nThe key is to make the experience enjoyable, insightful, and relevant for both you and your audience. Interactive presentations require careful planning and practice, but the payoff can be immense in terms of audience engagement and satisfaction.'\n"
     ]
    }
   ],
   "source": [
    "for chat in chat_history:\n",
    "    print(chat)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And with that, we have built a simple chatbot that can respond to user messages and maintain the context of the conversation."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
